<!-- 沟通记录添加页 -->
<template>
  <div style="width: 100%;overflow: hidden;">
    <van-calendar
      :show-confirm="false"
      v-model="ShowAccountingEndDate"
      @confirm="EndTime"
    />
    <van-popup
      v-model="show"
      position="left"
      class="fa"
      :style="{ height: '100%', width: '100%' }"
    >
      <div>
        <van-nav-bar
          title="新建沟通记录"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />

        <van-form
         ref="checkform"
          @submit="onSubmit"
          style="height: 100%;overflow: auto;box-sizing: border-box;"
        >
          <div class="client" style="padding-bottom: 70px;">
            <van-field
            required
              :rules="[{ required: true, message: '请填写客户名' }]"
              label="客户名称："
              v-model="entity.CustomerName"
              readonly
              placeholder="请选择客户"
              right-icon="edit"
              @click="CustomerChoice"
            >
            </van-field>
            <van-field
            required
              :rules="[{ required: true, message: '请选择日期' }]"
              label="日期"
              placeholder="请选择日期"
              :value="entity.DailyRecordDate"
              @click="ShowAccountingEndDate = true"
            />
            <van-field
            required
              label="标题："
                placeholder="请输入标题"
              v-model="entity.DailyRecordTitle"
              :rules="[{ required: true, message: '请输入标题' }]"
            >
            </van-field>
            <van-field
             placeholder="请选择抄送"
              label="抄送："
              readonly
              v-model="entity.SharerName"
              @click="showClick"
            >
            </van-field>

            <van-field
              label="关键字："
              placeholder="请使用【回车】分词"
              @keydown.enter.stop="down"
              v-model="keyword"
            >
            </van-field>
            <van-tag
              type="primary"
              v-for="(item, index) in WordList"
              :key="index"
              closeable
              class="tagClass"
              @close="closeTag(index)"
              >{{ item }}</van-tag
            >
            <!-- <span
            v-for="(item, index) in entity.DRKeyWordList"
            :key="index"
            @click="closeTag(index)"
            >{{ item }}</span
          > -->
          </div>
          <div class="scrollBar">
            <van-field
            required
              :rules="[{ required: true, message: '请输入交流内容' }]"
              label="交流内容:"
              v-model="entity.DailyRecord"
              type="textarea"
              placeholder="请输入交流内容"
              rows="1"
            >
            </van-field>
            <!-- <quill-editor
            class="editor"
            v-model="entity.DailyRecord"
            ref="myQuillEditor"
            @blur="onEditorBlur"
            @focus="onEditorFocus"
            @ready="onEditorReady"
          >
          </quill-editor> -->
            <van-field label="附件">
              <template #input>
                <!-- 考虑到除了新增，修改时也要用到这个页面，且只有单张照片，而且数据库里直接存的路径，在这里可以展示一下已经上传的图片，也可以做点击预览 -->
                <!-- <van-image
                :src="entity.reportPic"
                fit="contain"
                v-if="entity.reportPic !==''"
              /> -->
                <!-- 图片选择，上传前判断格式，删除前做数据处理  -->
                <van-uploader
                  v-model="fileList"
                  :after-read="afterRead"
                  :before-delete="beforeDelete"
                  :max-count="1"
                />
              </template>
            </van-field>
          </div>
        </van-form>
          <div class="submitButton"  v-show="hideshow" >
            <van-button  @click="buttonSubmitChange" round block type="info" native-type="submit"
              >提交</van-button
            >
          </div>
      </div>
      <Myuser @customerChoice="Client" ref="myuser" />
      <!-- <Product @Product="Product" ref="product" /> -->
      <!-- <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '5px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <van-button @click="close" slot="button" type="default"
          >关闭</van-button
        >
        <van-button @click="handleSubmit" slot="button" type="primary"
          >保存</van-button
        >
      </div> -->

      <van-popup
        class="popup"
        :close-on-click-overlay="true"
        position="bottom"
        :style="{ height: '50%', width: '100%' }"
        v-model="showUser"
      >
        <div class="confirmBtn">
          <van-button
            size="mini"
            class="comBtn"
            @click="showUser = false"
            type="danger"
            >取消</van-button
          >
          <van-button size="mini" class="comBtn" @click="confrim" type="info"
            >确认</van-button
          >
        </div>
        <div style="width: 100%;height: calc(100% - 50px);overflow-y: auto;">
          <van-list
            :immediate-check="false"
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            :offset="100"
            @load="onLoad"
          >
            <!-- <p v-for="item in data" :key="item.Id">{{ item.RealName }}</p> -->
            <van-cell
              v-for="item in data"
              :key="item.Id"
              :title="`${item.RealName}(${item.UserName})`"
              @click="cellItem(item)"
              :style="{ background: item.checked ? '#cdcdcd' : '#fff' }"
            />
          </van-list>
        </div>
      </van-popup>
    </van-popup>
  </div>
</template>

<script>
import { Icon } from "vant";
import { Popup } from "vant";
import { AddressList } from "vant";

import {
  Row,
  Col,
  Cell,
  CellGroup,
  Toast,
  NavBar,
  Divider,
  Uploader,
  Image
} from "vant";
import { Field, Calendar } from "vant";
//客户
import Myuser from "@/components/OwnUser.vue";
// import Product from "../../components/Product.vue";
export default {
  props: {
    parentObj: Object
  },
  components: {
    "van-calendar": Calendar,
    //分割线
    "van-divider": Divider,
    "van-nav-bar": NavBar,
    "van-icon": Icon,
    "van-popup": Popup,
    "van-row": Row,
    "van-address-list": AddressList,
    "van-field": Field,
    "van-col": Col,
    "van-cell": Cell,
    "van-cell-group": CellGroup,
    "van-image": Image,
    "van-uploader": Uploader,
    Myuser
    // Product
  },
  data() {
    return {
       // 解决表单输入移动端键盘弹起导致的页面fixed定位元素布局错乱问题
      docmHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      showHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      hideshow: true, //显示或者隐藏footer
      disabled:false,
      // 上传附件列表数据
      fileList: [],
      WordList: [],
      showUser: false,
      entity: {},
      data: [],
      ShowAccountingEndDate: false,
      show: false,
      Id: "",
      messages: [],
      info: "",
      keyword: "",
      loading: false,
      finished: false,
      PageRows: 20,
      PageIndex: 1,
      ids: [],
      thumbUrl: "",
      fileListData: []
    };
  },
  created() {
    this.openForm();
  },
   watch: {
    //监听显示高度
    showHeight: function() {
      if (this.docmHeight > this.showHeight) {
        //隐藏
        this.hideshow = false;
      } else {
        //显示
        this.hideshow = true;
      }
    }
  },
  mounted() {
    //监听事件
    window.onresize = () => {
      return (() => {
        this.showHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
      })();
    };
  },
  methods: {
    // 上传附件
    //图片选择后回调，这里就是重点了，就是在选择照片后，将照片的信息封装到FormData对象中
    //注意我这里是单图上传，所以直接new了，如果是多图的话，应该要考虑添加和删除FormData中的元素
    afterRead(file) {
      //创建FormData对象。上传图片需要转换二进制，这里要用到FormData
      let forms = new FormData();
      //"file"表示给后台传的属性名字
      forms.append("file", file.file); //获取上传图片信息
      this.fileListData = file;
      file.status = "uploading";
      file.message = "上传中...";
      this.reportPicUpload(forms, file);
    },
    //图片上传的前置处理 暂时不删除
    // beforeRead(file) {
    //     if (file.type !== 'image/jpeg' || file.type !== 'image/jpg' || file.type !== 'image/png') {
    //         Toast('请上传图片格式');
    //         return false;
    //     }
    //     return true;
    // },
    //图片上传，由提交按钮调用本方法实现手动上传
    reportPicUpload(params, file) {
      //如果文件列表为空，则不需要调用上传
      if (params == null || params.length == 0) {
        return;
      }
      this.http
        .post(
          "/CustomerManagement/SalesmanDailyRecord/UploadFileByForm",
          params
        )
        .then(res => {
          Toast.success("已上传");
          file.status = "done";
          if (res.thumbUrl) {
            this.thumbUrl = res.thumbUrl;
          } else {
            Toast.fail(res.msg);
          }
        })
        .catch(err => {
          Toast.fail("图片上传失败");
          setTimeout(() => {
            file.status = "failed";
            file.message = "上传失败";
          }, 1000);
        });
    },

    //图片删除前回调，删除时将公共变量forms中的文件信息一并删除
    beforeDelete(file) {
      forms = null;
      this.fileListData = [];
      return true;
    },
    onLoad() {
      // this.PageRows += 5;
      this.PageIndex++;
      this.getUserData();
      // this.loading = false;
    },
    swipeleft() {
      this.show = false;
      // alert("123");
    },
    touchstart(e) {
      // alert("123");

      // e.preventDefault();

      this.startX = e.touches[0].clientX;
      this.startY = e.touches[0].clientY;
    },
    touchmove(e) {
      // this.show = false;
      e.preventDefault();
      this.moveX = e.touches[0].clientX;
      this.moveY = e.touches[0].clientY;
      // this.startX - this.moveX <= 0
      //   ? console.log("你在往右滑")
      //   : console.log("你在往左滑");
    },

    closeTag(index) {
      console.log(index);
      this.WordList.splice(index, 1);
    },
    down() {
      if (!this.WordList) {
        this.WordList = [];
      }
      console.log(this.keyword);
      console.log(this.WordList);
      let a = this.WordList.includes(this.keyword);
      if (!a && this.keyword != "") {
        this.WordList.push(this.keyword);
      } else {
        Toast.fail("关键字不能重复或者为空");
      }
      this.keyword = "";
    },
    confrim() {
      console.log(this.data);
      let idsArrName = this.ids.map(item => {
        return item.RealName;
      });
      // let idsArrName = this.data
      //   .filter(item => item.checked == true)
      //   .map(item => item.RealName);
      this.entity.SharerName = idsArrName.join("|");
      let idsArr = this.ids.map(item => {
        return item.Id;
      });
      // let idsArr = this.data
      //   .filter(item => item.checked == true)
      //   .map(item => item.Id);
      // console.log(idsArr);
      this.entity.SharerIds = idsArr.join("|");
      this.showUser = false;
    },
    cellItem(item) {
      this.$set(item, "checked", !item.checked);
      console.log(item);
      if (item.checked) {
        this.ids.push(item);
      } else {
        var index = this.ids.findIndex(val => {
          return val.Id === item.Id;
        });
        this.ids.splice(index, 1);
      }
      console.log(item.checked);
      console.log(this.ids);
    },
    showClick() {
      this.showUser = true;
    },
    onEditorBlur() {
      console.log("blur", this.messages);
    },

    onEditorFocus() {
      console.log("focus", this.messages);
    },

    onEditorReady() {
      console.log("ready", this.messages);
    },

    formatDate(date) {
      var time = new Date(date);
      var y = time.getFullYear();

      return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    EndTime(date) {
      this.ShowAccountingEndDate = false;
      this.entity.DailyRecordDate = this.formatDate(date);
    },
    //返回
    onClickLeft() {
      this.show = false;
      this.$router.go(-1);
    },
    //选中的产品
    Product(a) {
      console.log(a, "选择产品信息");

      this.data.push({
        ProductId: a.cInvCode,
        cInvName: a.cInvName,
        cInvCode: a.cInvCode,
        cInvStd: a.cInvStd
      });
    },

    close() {
      this.show = false;
      this.entity = {};
      this.$router.go(-1);
    },
    Client(a) {
      console.log(a);
      this.$set(this.entity, "CustomerName", a.cCusName);

      this.entity.CustomerId = a.Id;
    },
    //选择客户
    CustomerChoice() {
      this.$refs.myuser.openForm();
    },
    getUserData() {
      this.http
        .post("/Base_Manage/Base_User/GetDataList", {
          PageIndex: this.PageIndex,
          PageRows: 20,
          SortField: "CreateTime",
          SortType: "desc",
          Search: {}
        })
        .then(resJson => {
          // this.data = [this.data, ...resJson.Data];
          resJson.Data.forEach(item => {
            this.data.push(item);
          });

          this.loading = false;
          if (this.data.length >= resJson.Total) {
            this.finished = true;
          } else {
            this.finished = false;
          }
        });
    },
    init() {
      this.show = true;
      this.data = [];
      this.WordList = [];
      this.entity = { DailyRecordDate: this.formatDate(new Date()) };
      this.getUserData();
      this.http.post("/Base_Manage/Home/GetOperatorInfo").then(resJson => {
        this.info = resJson.Data.UserInfo;
      });
    },
     // 使用ref进行表单提交。。防止关键字输入后电脑按键回车或者手机按键回车直接提交或者跳转下一步了
    buttonSubmitChange() {
      this.$refs.checkform.submit();
    },
    onSubmit() {
      this.entity.SalesmanName = this.info.RealName;
      this.entity.DRKeyWordList = this.WordList;
      this.entity.File = [this.thumbUrl];
      let obj = {
        FileURL: this.thumbUrl
      };
      let arr = [];
      arr.push(obj);
      this.entity.SDRDTOList = arr;

      console.log(this.info.RealName);
      //   this.entity.DailyRecordDate = `${this.entity.DailyRecordDate} 00:00:00`;

      this.http
        .post("/CustomerManagement/SalesmanDailyRecord/SaveData", this.entity)
        .then(res => {
          console.log(res);
          if (res.Success) {
            this.show = false;
            Toast.success("操作成功");
            this.$router.push("/Communication");
            // this.parentObj.getDataList();
            setTimeout(() => {
              this.btnLoading = false;
            }, 500);
          } else {
            Toast(res.Msg);
          }
        });
    },
    openForm() {
      this.init();
    }
  }
};
</script>

<style>
.popup {
  border-radius: 20px 20px 0 0;
}
.comBtn {
  border-radius: 2px;
  margin-top: 5px;
}
.content {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 5;
  overflow: hidden;
}
.confirmBtn {
  /* position: fixed;
  top: 50%; */
  width: 100%;
  display: flex;
  /* height: 30px; */
  justify-content: space-between;
  padding: 10px;
  line-height: 2;
  background-color: #fff;
  box-sizing: border-box;
  z-index: 100;
  border-radius: 20px 20px 0 0;
}
.scrollBar {
  /* height: calc(100vh - 230px); */
  /* padding-bottom: 80px; */
  /* overflow: auto; */
}
.close {
  position: fixed;

  right: 0;
  bottom: 0;
  padding: "5px 16px";
  background: "#fff";
  text-align: right;
  z-index: 1;
}
.client {
  box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
}
.box {
  width: 80%;
  height: 200px;
  overflow: auto;
  margin: 0 auto;

  border: 1px solid #ccc;
  /* box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 10px 10px; */

  margin-top: 20px;
  margin-bottom: 10px;
}
.tagClass {
  color: #000;
  padding: 5px;
  background-color: #ccc;
  border-radius: 8px;
  margin-left: 5px;
}
</style>
